

package com.jysz.certificate.service.generator;

import java.sql.SQLException;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.HibernateTemplate;

import com.jysz.certificate.persistence.model.system.SequenceNumber;
import com.jysz.certificate.persistence.model.system.SequenceNumber.SequenceType;


/**
 * 抽象的代类
 * 
 * @author <a href="mailto:javaengine@outlook.com">Kaca Rich</a>
 *
 */
public abstract class AbstractGeneratorDelegate implements IGeneratorDelegate {
	
	public static final String DEFAULT_STRING_FORMAT="%1$d";
	protected abstract String getEntityClassName();
	protected abstract SequenceType getSequenceType();

	/**
	 * @see com.jysz.certificate.service.generator.IGeneratorDelegate#findCurrentSeqNumber(org.springframework.orm.hibernate3.HibernateTemplate)
	 */
	@SuppressWarnings("unchecked")
	public SequenceNumber findCurrentSeqNumber(HibernateTemplate ht) {
		return ht.execute(new HibernateCallback<SequenceNumber>() {
	
			public SequenceNumber doInHibernate(Session session)
					throws HibernateException, SQLException {
				Criteria c = session.createCriteria(SequenceNumber.class);
				c.add(Restrictions.eq(SequenceNumber.SEQ_TYPE_PRO_NAME, getSequenceType())).add(
						Restrictions.eq(SequenceNumber.ENTITY_CLAZZ_NAME_PRO_NAME, getEntityClassName()));
				//FIXME why can't do here 
//				CommonStaticUtils.EntityResultTransformer(c, SequenceNumber.class);
				List<SequenceNumber> r = c.list();
				if (r.size() == 0) {
					return null;
				}
				return r.get(0);
			}
		});
	}

	/**
	 * @see com.jysz.certificate.service.generator.IGeneratorDelegate#newSequenceNumber(org.springframework.orm.hibernate3.HibernateTemplate)
	 */
	public SequenceNumber newSequenceNumber(HibernateTemplate ht) {
		SequenceNumber seq = new SequenceNumber();
		seq.setCurrentNum(0);
		seq.setStepNum(1);
		seq.setEntityClazzName(getEntityClassName());
		seq.setLengthLimited(8);
		seq.setSeqFormat(DEFAULT_STRING_FORMAT);
		seq.setSeqType(getSequenceType());
		return seq;
	}
}